package com.lz.gmall.product.service.impl;
import java.math.BigDecimal;
import com.google.common.collect.Lists;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lz.gamll.feign.search.GoodsFeignClient;
import com.lz.gmall.product.biz.CategoryBizService;
import com.lz.gmall.product.biz.SkuDetailBizService;
import com.lz.gmall.product.dto.SkuInfoDto;
import com.lz.gmall.product.entity.*;
import com.lz.gmall.product.mapper.BaseTrademarkMapper;
import com.lz.gmall.product.mapper.SkuAttrValueMapper;
import com.lz.gmall.product.service.SkuAttrValueService;
import com.lz.gmall.product.service.SkuImageService;
import com.lz.gmall.product.service.SkuInfoService;
import com.lz.gmall.product.mapper.SkuInfoMapper;
import com.lz.gmall.product.service.SkuSaleAttrValueService;
import com.lz.gmall.product.vo.CategoryViewVo;
import com.lz.gmall.product.vo.CategoryVo;
import com.lz.gmall.properties.ThreadPoolProperties;
import com.lz.gmall.search.entity.Goods;
import com.lz.gmall.search.entity.SearchAttr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@Slf4j
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoMapper, SkuInfo>
    implements SkuInfoService{

    @Autowired
    private SkuImageService skuImageService;

    @Autowired
    private SkuAttrValueService skuAttrValueService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private GoodsFeignClient goodsFeignClient;

    @Autowired
    private SkuDetailBizService skuDetailBizService; //用户构建goods所需的参数

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    /**
     *获取sku分页列表
     * @param pageNum 页码
     * @param limit 每页条数
     * @return
     */
    @Override
    public Page<SkuInfo> getSkuInfoByPage(Long pageNum, Long limit) {
        Page<SkuInfo> page = new Page<>(pageNum, limit);
        page(page);
        return page;
    }

    /**
     * 添加sku
     * @param skuInfoDto sku数据
     */
    @Override
    @Transactional
    public void saveSkuInfo(SkuInfoDto skuInfoDto) {
        // 保存SKU基本信息
        SkuInfo skuInfo = new SkuInfo();
        BeanUtils.copyProperties(skuInfoDto,skuInfo);
        save(skuInfo);

        // 保存sku图片信息
        List<SkuImage> skuImageList = skuInfoDto.getSkuImageList();
        skuImageList = skuImageList.stream().map(skuImage -> {
            skuImage.setSkuId(skuInfo.getId());
            return skuImage;
        }).collect(Collectors.toList());
        skuImageService.saveBatch(skuImageList);

        // 保存SKU平台属性值信息
        List<SkuAttrValue> skuAttrValueList = skuInfoDto.getSkuAttrValueList();
        skuAttrValueList = skuAttrValueList.stream().map(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            return skuAttrValue;
        }).collect(Collectors.toList());
        skuAttrValueService.saveBatch(skuAttrValueList);

        // 保存SKU销售属性值信息
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfoDto.getSkuSaleAttrValueList();
        skuSaleAttrValueList = skuSaleAttrValueList.stream().map(skuSaleAttrValue -> {
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            return skuSaleAttrValue;
        }).collect(Collectors.toList());
        skuSaleAttrValueService.saveBatch(skuSaleAttrValueList);
    }

    /**
     * 上架操作,商家产品的同时把商品数据加入es数据库
     * @param skuId
     */
    @Override
    public void onSale(Long skuId) {

        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale((byte) 1);
        updateById(skuInfo);

        Goods goods = GoodsBuild(skuId);

        goodsFeignClient.saveGoods(goods);
    }

    /**
     * 构建要传入es检索库的商品（goods）
     * @param skuId sku商品的id
     * @return
     */
    private Goods GoodsBuild(Long skuId) {
        Goods goods = new Goods();

        //SkuInfo skuInfo = null;
        SkuInfo skuInfo = skuDetailBizService.getSkuInfoAndImageById(skuId);

        CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> {
            //获取展示商品的基本信息
            goods.setId(skuId);
            goods.setDefaultImg(skuInfo.getSkuDefaultImg());
            goods.setTitle(skuInfo.getSkuName()); //进行分词查询
            goods.setPrice(skuInfo.getPrice());
            goods.setCreateTime(new Date());
            log.info("获取展示商品的基本信息..成功了");
        }, threadPoolExecutor);

        CompletableFuture<Void> cf2 = CompletableFuture.runAsync(() -> {
            //获取展示商品的平台属性和平台属性值
            CategoryViewVo categoryViewVo = skuDetailBizService.getCategoryViewBySkuId(skuId);
            goods.setCategory1Id(categoryViewVo.getCategory1Id());
            goods.setCategory1Name(categoryViewVo.getCategory1Name());
            goods.setCategory2Id(categoryViewVo.getCategory2Id());
            goods.setCategory2Name(categoryViewVo.getCategory2Name());
            goods.setCategory3Id(categoryViewVo.getCategory3Id());
            goods.setCategory3Name(categoryViewVo.getCategory3Name());
            log.info("获取展示商品的平台属性和平台属性值..成功了");
        }, threadPoolExecutor);

        CompletableFuture<Void> cf3 = CompletableFuture.runAsync(() -> {
            //获取展示商品的品牌属性
            BaseTrademark baseTrademark = baseTrademarkMapper.selectById(skuInfo.getTmId());
            goods.setTmId(baseTrademark.getId());
            goods.setTmName(baseTrademark.getTmName());
            goods.setTmLogoUrl(baseTrademark.getLogoUrl());
            log.info("获取展示商品的品牌属性..成功了");
        }, threadPoolExecutor);

        CompletableFuture<Void> cf4 = CompletableFuture.runAsync(() -> {
            //获取展示该商品对应的所有平台属性和平台属性值
            List<SearchAttr> searchAttrList = skuAttrValueMapper.getAttrsBySkuId(skuId);
            goods.setAttrs(searchAttrList);
            log.info("获取展示该商品对应的所有平台属性和平台属性值..成功了");
        }, threadPoolExecutor);

        CompletableFuture.allOf(cf1,cf2,cf3,cf4).join();

        goods.setHotScore(0L);

        return goods;

    }

    /**
     * 下架操作,同时把加入es数据库中的商品删除掉
     * @param skuId
     */
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale((byte) 0);
        updateById(skuInfo);

        goodsFeignClient.deleteGoodsById(skuId);
    }
}




